package com.csap.framework.oauth2.security;

import cn.dev33.satoken.oauth2.logic.type.SecurityStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户信息本地缓存
 *
 * @Author ycf
 * @Date 2023/6/13 00:00
 * @Version 1.0
 */
@Slf4j
public class RouterCache {

    private static final Map<SecurityStrategy, Map<HttpMethod, Map<String, Boolean>>> LOADING_CACHE = new ConcurrentHashMap<>();


    public static void clear() {
        LOADING_CACHE.clear();
    }

    /**
     * 获取用户信息
     *
     * @param key    标识
     * @param method 方法
     * @param path   请求地址
     * @return 结果
     */
    public static Boolean getOrNull(SecurityStrategy key, HttpMethod method, String path) {
        return computeIfAbsent(key, method).getOrDefault(path, null);
    }

    /**
     * 获取用户信息
     *
     * @param key    标识
     * @param method 方法
     * @return 结果
     */
    public static Map<String, Boolean> computeIfAbsent(SecurityStrategy key, HttpMethod method) {
        return LOADING_CACHE.computeIfAbsent(key, i -> new ConcurrentHashMap<>(16))
                .computeIfAbsent(method, i -> new ConcurrentHashMap<>(16));
    }

    /**
     * 处理地址
     *
     * @param key     策略键
     * @param method  方法
     * @param path    路径
     * @param exclude 是否不包含
     * @return 结果
     */
    public static Boolean computeIfAbsent(SecurityStrategy key, HttpMethod method, String path, Boolean exclude) {
        return computeIfAbsent(key, method).computeIfAbsent(path, i -> exclude);
    }
}
